<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PicShare - 设置</title>
    <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
    <div class="app-container">
        <!-- Navigation -->
        <nav class="navbar">
            <div class="navbar-content">
                <a href="/" class="navbar-brand">📸 PicShare</a>
                
                <div class="navbar-menu">
                    <span>欢迎, <span th:text="${user.nickname}"></span></span>
                    <a href="/">返回首页</a>
                    <a href="/logout">退出</a>
                </div>
            </div>
        </nav>
        
        <!-- Settings Content -->
        <div class="settings-container">
            <h1>账户设置</h1>
            
            <div class="user-info">
                <h3>用户信息</h3>
                <div style="display: flex; gap: 30px; align-items: center;">
                    <p><strong>用户名:</strong> <span th:text="${user.username}"></span></p>
                    <p><strong>昵称:</strong> <span th:text="${user.nickname}"></span></p>
                </div>
            </div>
            
            <div th:if="${error}" class="alert alert-danger" th:text="${error}"></div>
            <div th:if="${success}" class="alert alert-success" th:text="${success}"></div>
            
            <form th:action="@{/settings/change-password}" method="post">
                <h3>修改密码</h3>
                
                <div class="form-group">
                    <label for="oldPassword">当前密码</label>
                    <input type="password" id="oldPassword" name="oldPassword" required>
                </div>
                
                <div class="form-group">
                    <label for="newPassword">新密码</label>
                    <input type="password" id="newPassword" name="newPassword" required>
                </div>
                
                <div class="form-group">
                    <label for="confirmPassword">确认新密码</label>
                    <input type="password" id="confirmPassword" name="confirmPassword" required>
                </div>
                
                <button type="submit" class="btn">修改密码</button>
            </form>
            
            <hr style="margin: 40px 0; border: none; border-top: 1px solid #e1e5e9;">
            
            <form th:action="@{/settings/update-server}" method="post">
                <h3>服务器配置</h3>
                <p style="color: #666; font-size: 14px; margin-bottom: 20px;">
                    配置服务器的IP地址和端口，用于生成分享链接。默认为 localhost:9500
                </p>
                
                <div class="form-group">
                    <label for="serverIp">服务器IP地址</label>
                    <input type="text" id="serverIp" name="serverIp" th:value="${serverIp}" required 
                           placeholder="例如: 192.168.1.100 或 example.com">
                </div>
                
                <div class="form-group">
                    <label for="serverPort">服务器端口</label>
                    <input type="number" id="serverPort" name="serverPort" th:value="${serverPort}" required 
                           min="1" max="65535" placeholder="例如: 9500">
                </div>
                
                <div class="form-group">
                    <label>当前分享链接前缀</label>
                    <div style="background: #f8f9fa; padding: 10px; border-radius: 6px; font-family: monospace; font-size: 14px;">
                        http://<span th:text="${serverIp}">localhost</span>:<span th:text="${serverPort}">9500</span>
                    </div>
                </div>
                
                <button type="submit" class="btn">更新服务器配置</button>
            </form>
            
            <hr style="margin: 40px 0; border: none; border-top: 1px solid #e1e5e9;">
            
            <!-- API Key管理 -->
            <div class="api-key-section">
                <h3>API Key管理</h3>
                <p style="color: #666; font-size: 14px; margin-bottom: 20px;">
                    用于客户端程序认证的API密钥。每个用户只能有一个API Key。
                </p>
                
                <div class="api-key-controls">
                    <button type="button" id="generateApiKeyBtn" class="btn">生成API Key</button>
                </div>
                
                <div id="apiKeyDisplay" class="api-key-display" style="display: none; margin-top: 20px;">
                    <div class="form-group">
                        <label>API Key</label>
                        <input type="text" id="apiKeyText" class="api-key-input" readonly>
                    </div>
                    <div class="api-key-buttons">
                        <button type="button" id="copyApiKeyBtn" class="btn" style="background-color: #28a745;">复制</button>
                        <button type="button" id="deleteApiKeyBtn" class="btn" style="background-color: #dc3545;">删除</button>
                    </div>
                    <div id="apiKeyInfo"></div>
                </div>
            </div>
        </div>
    </div>
    
    <style>
        .api-key-section {
            background: white;
            border-radius: 8px;
            padding: 0;
        }
        
        .api-key-controls {
            margin-bottom: 20px;
        }
        
        .api-key-display {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 20px;
            border: 1px solid #e9ecef;
        }
        
        .api-key-input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            background: white;
            font-family: monospace;
            font-size: 14px;
            box-sizing: border-box;
        }
        
        .api-key-buttons {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
        
        .alert {
            padding: 12px;
            border-radius: 4px;
            margin-top: 10px;
        }
        
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .alert-info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
    </style>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const generateBtn = document.getElementById('generateApiKeyBtn');
            const copyBtn = document.getElementById('copyApiKeyBtn');
            const deleteBtn = document.getElementById('deleteApiKeyBtn');
            const apiKeyDisplay = document.getElementById('apiKeyDisplay');
            const apiKeyText = document.getElementById('apiKeyText');
            const apiKeyInfo = document.getElementById('apiKeyInfo');
            
            // 生成API Key
            generateBtn.addEventListener('click', async function() {
                try {
                    const response = await fetch('/settings/api/generate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        apiKeyText.value = result.apiKey;
                        apiKeyDisplay.style.display = 'block';
                        apiKeyInfo.innerHTML = '<div class="alert alert-success">' + result.message + '</div>';
                        generateBtn.disabled = true;
                    } else {
                        apiKeyInfo.innerHTML = '<div class="alert alert-danger">' + result.message + '</div>';
                    }
                } catch (error) {
                    apiKeyInfo.innerHTML = '<div class="alert alert-danger">生成失败：' + error.message + '</div>';
                }
            });
            
            // 复制API Key
            copyBtn.addEventListener('click', async function() {
                try {
                    // 使用现代的Clipboard API
                    await navigator.clipboard.writeText(apiKeyText.value);
                    
                    const originalText = copyBtn.textContent;
                    copyBtn.textContent = '已复制！';
                    copyBtn.style.backgroundColor = '#28a745';
                    
                    setTimeout(() => {
                        copyBtn.textContent = originalText;
                        copyBtn.style.backgroundColor = '#28a745';
                    }, 2000);
                } catch (err) {
                    // 如果现代API不可用，降级到传统方法
                    apiKeyText.select();
                    apiKeyText.setSelectionRange(0, 99999);
                    document.execCommand('copy');
                    
                    const originalText = copyBtn.textContent;
                    copyBtn.textContent = '已复制！';
                    copyBtn.style.backgroundColor = '#28a745';
                    
                    setTimeout(() => {
                        copyBtn.textContent = originalText;
                        copyBtn.style.backgroundColor = '#28a745';
                    }, 2000);
                }
            });
            
            // 删除API Key
            deleteBtn.addEventListener('click', async function() {
                if (confirm('确定要删除API Key吗？删除后客户端将无法使用。')) {
                    try {
                        const response = await fetch('/settings/api/delete', {
                            method: 'POST'
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            apiKeyDisplay.style.display = 'none';
                            apiKeyText.value = '';
                            apiKeyInfo.innerHTML = '<div class="alert alert-success">' + result.message + '</div>';
                            generateBtn.disabled = false;
                        } else {
                            apiKeyInfo.innerHTML = '<div class="alert alert-danger">' + result.message + '</div>';
                        }
                    } catch (error) {
                        apiKeyInfo.innerHTML = '<div class="alert alert-danger">删除失败：' + error.message + '</div>';
                    }
                }
            });
            
            // 页面加载时自动检查API Key状态
            async function checkApiKeyStatus() {
                try {
                    const response = await fetch('/settings/api/status');
                    const result = await response.json();
                    
                    if (result.hasApiKey) {
                        apiKeyText.value = result.apiKey;
                        apiKeyDisplay.style.display = 'block';
                        const createdDate = new Date(result.created);
                        apiKeyInfo.innerHTML = '<div class="alert alert-success">API Key已存在，创建时间：' + createdDate.toLocaleString() + '</div>';
                        generateBtn.disabled = true;
                    } else {
                        apiKeyDisplay.style.display = 'none';
                        apiKeyInfo.innerHTML = '';
                        generateBtn.disabled = false;
                    }
                } catch (error) {
                    console.error('检查API Key状态失败:', error);
                }
            }
            
            // 自动检查API Key状态
            checkApiKeyStatus();
        });
    </script>
</body>
</html>